package com.jine.boot7.suer.controller;

import com.jine.boot7.suer.model.SUser;
import com.jine.boot7.suer.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("suser")
public class SUserController {

    @Autowired
    private SUserService sUserService;

    @RequestMapping("/")
    public String index(){
        return "index";
    }

    /**
     * 新增用户
     * @param name
     * @param pass
     * @return
     */
    @ResponseBody
    @PostMapping("/save")
    public Map<String,Object> saveUser(@RequestParam("name") String name, @RequestParam("pass") String pass){
        Map<String,Object> map = new HashMap<String,Object>();
        SUser user = new SUser();
        user.setUsername(name);
        user.setUserpass(pass);
        user.setRegdate(new Date());
        this.sUserService.saveUser(user);
        map.put("user",user);
        return map;
    }

    /**
     * 获取所有用户
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    public Map<String, List<SUser>> listUser(){
        Map<String,List<SUser>> map = new HashMap<String,List<SUser>>();
        List<SUser> list =this.sUserService.listUser();
        map.put("userList",list);
        return map;
    }

    /**
     * 查询一个用户
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("find")
    public Map<String,Object> findUser(@RequestParam("id") String id){
        Map<String,Object> map = new HashMap<String,Object>();
        SUser user  = this.sUserService.findUser(id);
        map.put("user",user);
        return map;
    }

    /**
     * 更新用户姓名
     * @param id
     * @param name
     * @return
     */
    @ResponseBody
    @PostMapping("update")
    public Map<String,Object> updateUser(@RequestParam("id") String id,@RequestParam("name") String name){
        Map<String,Object> map = new HashMap<String,Object>();
        SUser user = this.sUserService.findUser(id);
        user.setUsername(name);
        this.sUserService.updateUser(user);
        map.put("result","RC100");
        return map;
    }
    /**
     * 删除一个用户
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("delete")
    public Map<String,Object> deleteUser(@RequestParam("id") String id){
        Map<String,Object> map = new HashMap<String,Object>();
        this.sUserService.deleteUser(id);
        map.put("result","RC100");
        return map;
    }

}
